let socket;
let constWBT = {};
let _that;
constWBT.ALARM_INFO = "ALARM_INFO"; //获取报警信息
constWBT.ALARM_SUCCESS = "ALARM_SUCCESS"; //获取报警信息
constWBT.LIVE_CAR = "LIVE_CAR";//作业看板车辆实时定位信息
constWBT.LIVE_CAR_ON = "LIVE_CAR_ON"//开始请求
constWBT.LIVE_CAR_OFF = "LIVE_CAR_OFF"//结束请求
constWBT.reConnectInterval = null;//websocket重新链接的定时任务
//心跳状态  为false时不能执行操作 等待重连
constWBT.isHeartflag = false;
//重连状态  避免不间断的重连操作
constWBT.isReconnect = false;
//初始化websocket连接
const initWs = function (url, those) {
  _that = those;
  //心跳状态  为false时不能执行操作 等待重连
  constWBT.isHeartflag = false;
  //重连状态  避免不间断的重连操作
  constWBT.isReconnect = false;

  window.WebSocket = window.WebSocket || window.MozWebSocket;
  if (!window.WebSocket) { // 检测浏览器支持
    _that.$util.notify.error("浏览器不支持websocket");
    return;
  }
  var token = _that.$storage.getToken();
  url = url + '/'
  if (token) {
    url = url + token;
  } else {
    url = url + 'NoUser';
  }
  socket = new WebSocket(url); // 创建连接并注册响应函数
  socket.onopen = function (e) {
    constWBT.isHeartflag = true;
    console.log("open");
  };
  socket.onmessage = function (e) {
    var data = eval('(' + e.data + ')');
    if (data.success) {
      //处理各种推送消息
      wsMethods.handleEvent(data);
    } else {
      console.log('websocket消息接收异常');
    }
  };
  socket.onclose = function () {
    socket = null; // 清理
    if (constWBT.isReconnect) {
      console.log('close');
      wsMethods.reConnect();
    }
  };
  socket.onerror = function () {
    console.log('error')
    constWBT.isHeartflag = false;
    wsMethods.reConnect();
  }
};
const wsMethods = {
  //重连 
  reConnect: function () {
    if (constWBT.isReconnect) return;
    constWBT.isReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    constWBT.reConnectInterval = setTimeout(function () {
      initWs()
      constWBT.isReconnect = false;
    }, 30000);
  },
  //处理消息
  handleEvent: function (res) {
    console.log(res)
    if (res.type == constWBT.ALARM_SUCCESS) {//链接成功
      wsMethods.sendMsg(constWBT.ALARM_INFO, '', {})//查询报警信息
    }
    else if (res.type == constWBT.ALARM_INFO) {
      //获取报警信息
      let num = _that.$store.state.app.notiNum;
      _that.$store.commit('setNotiNum', ++num);
    }
  },
  //发送消息
  sendMsg: function (type, target, data) {
    let params = {
      type: type,
      target: target,
      reason: '',
      success: false,
      message: '',
      dealwith: '',
      progress: "",
      data: data
    }
    if (socket) {
      socket.send(JSON.stringify(params));
    } else {
      console.log('与服务器断开连接');
      initWs(api.websocketUrl, _that);
    }
  },
};
export {
  constWBT,
  initWs,
  socket,
  wsMethods
}
